package Day012_多线程2.ZuoYe;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * @author zhangyan
 * @date 2020/4/30 17:50
 */
public class Test3_5 {
    public static void main(String[] args) {

        //创建CyclicBarrier对象
        CyclicBarrier cb = new CyclicBarrier(3,new MyRunnable4());

        MyRunnable1 mr1 = new MyRunnable1(cb);
        MyRunnable2 mr2 = new MyRunnable2(cb);
        MyRunnable3 mr3 = new MyRunnable3(cb);

        new Thread(mr1).start();
        new Thread(mr2).start();
        new Thread(mr3).start();
    }
}

class MyRunnable1 implements Runnable {
    CyclicBarrier cb;

    public MyRunnable1(CyclicBarrier cb) {
        this.cb = cb;
    }

    @Override
    public void run() {
        int sum = 0;
        for (int i = 1; i <= 10000; i++) {
            sum += i;
        }
        System.out.println("1-10000所有整数和:" + sum);
        try {
            cb.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (BrokenBarrierException e) {
            e.printStackTrace();
        }
    }
}

class MyRunnable2 implements Runnable {
    CyclicBarrier cb;

    public MyRunnable2(CyclicBarrier cb) {
        this.cb = cb;
    }

    @Override
    public void run() {
        int sum = 0;
        for (int i = 1; i <= 10000; i++) {
            if (i % 2 == 0) {
                sum += i;
            }
        }
        System.out.println("1-10000所有偶数和:" + sum);
        try {
            cb.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (BrokenBarrierException e) {
            e.printStackTrace();
        }
    }
}

class MyRunnable3 implements Runnable {
    CyclicBarrier cb;

    public MyRunnable3(CyclicBarrier cb) {
        this.cb = cb;
    }

    @Override
    public void run() {
        int sum = 0;
        for (int i = 1; i <= 10000; i++) {
            if (i % 2 != 0) {
                sum += i;
            }
        }
        System.out.println("1-10000所有奇数和:" + sum);
        try {
            cb.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (BrokenBarrierException e) {
            e.printStackTrace();
        }
    }
}

class MyRunnable4 implements Runnable {

    @Override
    public void run() {
        System.out.println("计算完毕");
    }
}